package org.jeecg.modules.demo.weixin.payorder.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.response.AlipayTradePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.demo.api.UpmsHelloApi;
import org.jeecg.modules.demo.config.MyConfig;
import org.jeecg.modules.demo.entity.Dept;
import org.jeecg.modules.demo.mall.api.MallHelloApi;
import org.jeecg.modules.demo.mall.dto.ProductNumDto;
import org.jeecg.modules.demo.mall.entity.YxStoreCouponUser;
import org.jeecg.modules.demo.mall.entity.YxSystemUserLevel;
import org.jeecg.modules.demo.mall.entity.YxUser;
import org.jeecg.modules.demo.util.ProfitUtil;
import org.jeecg.modules.demo.weixin.dto.PayDto;
import org.jeecg.modules.demo.weixin.dto.PayValues;
import org.jeecg.modules.demo.weixin.dto.ProfitSharingDto;
import org.jeecg.modules.demo.weixin.entity.*;
import org.jeecg.modules.demo.weixin.merchantpay.service.IMerchantPayService;
import org.jeecg.modules.demo.weixin.payorder.mapper.PayOrderMapper;
import org.jeecg.modules.demo.weixin.payorder.service.IPayOrderService;
import org.jeecg.modules.demo.weixin.smtdev.service.ISmtDevService;
import org.jeecg.modules.demo.weixin.smtmerchantprice.service.ISmtMerchantPriceService;
import org.jeecg.modules.demo.weixin.smtmerchantshoprecord.service.ISmtMerchantShopRecordService;
import org.jeecg.modules.demo.weixin.smtoncecardusers.service.ISmtOnceCardUsersService;
import org.jeecg.modules.demo.weixin.smtsharingmember.service.ISmtSharingMemberService;
import org.jeecg.modules.demo.weixin.smtsplitmerchant.service.ISmtSplitMerchantService;
import org.jeecg.modules.demo.weixin.smtsplitordercom.service.ISmtSplitOrderComService;
import org.jeecg.modules.demo.weixin.smtsplitorderfee.service.ISmtSplitOrderFeeService;
import org.jeecg.modules.demo.weixin.smtsplitrecord.service.ISmtSplitRecordService;
import org.jeecg.modules.demo.weixin.smtsplitrulecom.service.ISmtSplitRuleComService;
import org.jeecg.modules.demo.weixin.smtsplitrulefee.service.ISmtSplitRuleFeeService;
import org.jeecg.modules.demo.weixin.smtstoreduserpoint.service.ISmtStoredUserPointService;
import org.jeecg.modules.demo.weixin.smtyuyuelist.service.ISmtYuyueListService;
import org.jeecg.modules.demo.weixin.smtyuyueuser.mapper.SmtYuyueUserMapper;
import org.jeecg.modules.demo.weixin.smtyuyueuser.service.ISmtYuyueUserService;
import org.jeecg.modules.demo.weixin.util.PayConstants;
import org.jeecg.modules.demo.weixin.util.ZhiFuBaoUtils;
import org.jeecg.modules.demo.weixin.vo.CouponUserVo;
import org.jeecg.modules.demo.weixin.vo.ProfitVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @Description: pay_order
 * @Author: jeecg-boot
 * @Date: 2023-10-23
 * @Version: V1.0
 */
@Slf4j
@Service
public class PayOrderServiceImpl extends ServiceImpl<PayOrderMapper, PayOrder> implements IPayOrderService {
    @Autowired
    private MallHelloApi mallHelloApi;

    @Autowired
    private ISmtMerchantPriceService smtMerchantPriceService;
    @Autowired
    private ISmtYuyueListService yuyueListService;
    @Autowired
    private ISmtSplitRecordService smtSplitRecordService;

    @Autowired
    private ISmtYuyueUserService yuyueUserService;
    @Resource
    private SmtYuyueUserMapper smtYuyueUserMapper;
    @Autowired
    private ISmtSplitRuleComService smtSplitRuleComService;
    @Autowired
    private ISmtOnceCardUsersService smtOnceCardUsersService;
    @Autowired
    private ISmtMerchantShopRecordService smtMerchantShopRecordService;
    @Autowired
    private IMerchantPayService merchantPayService;

    @Autowired
    private ISmtSplitOrderFeeService smtSplitOrderFeeService;

    @Autowired
    private ISmtSplitRuleFeeService smtSplitRuleFeeService;

    @Autowired
    private ISmtDevService smtDevService;

    @Autowired
    private ISmtStoredUserPointService smtStoredUserPointService;
    @Autowired
    private UpmsHelloApi upmsHelloApi;

    @Autowired
    private ISmtSplitOrderComService smtSplitOrderComService;

    @Autowired
    private ISmtSplitMerchantService smtSplitMerchantService;

    @Autowired
    private ISmtSharingMemberService smtSharingMemberService;

    /**
     * 调用微信支付
     *
     * @param payDto
     * @param orderId
     * @return
     */
    @SneakyThrows
    @Override
    public Map<String, String> payOrder(PayDto payDto, Integer orderId) {
        //根据商家id查询商家配置的支付信息
        QueryWrapper<MerchantPay> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("merchant_id", Integer.valueOf(payDto.getMerId()));
        MerchantPay merchantPay = merchantPayService.getOne(queryWrapper);
        //微信支付的单位是分，要转换一下
        String amount = String.valueOf(payDto.getPayPrice().multiply(BigDecimal.valueOf(100)).intValue());
        //生成随机数
        String nonceStr = WXPayUtil.generateNonceStr();
        //格式化返回数据
        //接收返回参数

//        WXPay wxPay = new WXPay(config);
        SortedMap<String, String> jsonParams = new TreeMap<>();
        jsonParams.put("appid", merchantPay.getAppId());
        jsonParams.put("mch_id", merchantPay.getMchId());
        jsonParams.put("nonce_str", nonceStr);
        jsonParams.put("body", "购买商品！");
        jsonParams.put("out_trade_no", String.valueOf(orderId));
        jsonParams.put("total_fee", amount);
        jsonParams.put("spbill_create_ip", payDto.getSpbillCreateIp());
        jsonParams.put("auth_code", payDto.getAuthCode());
        //生成签名
        String sign = WXPayUtil.generateSignature(jsonParams, merchantPay.getApiKey());
        jsonParams.put("sign", sign);

        //接收返回参数
//        Map<String, String> result = wxPay.microPay(jsonParams);
//        return result;
        return null;
    }


    /**
     * 支付宝服务上支付
     *
     * @param payDto
     * @param payOrder
     * @param orderId
     * @return
     */
    @SneakyThrows
    @Override
    public Result<?> serviceAlipayOrder(PayDto payDto, PayOrder payOrder, Integer orderId) {
        Dept dept = upmsHelloApi.queryByDept(Long.valueOf(payDto.getMerId()));
        if (dept == null) {
            return Result.error("门店不存在");
        }
        if (StringUtils.isBlank(dept.getZfbMerId()) && StringUtils.isBlank(dept.getZfbToken())) {
            return Result.error("请先配置支付宝商家支付信息！");
        }
        AlipayTradePayResponse zhifub = ZhiFuBaoUtils.zhifub(String.valueOf(orderId), dept.getZfbToken(), dept.getZfbMerId(), payDto, payOrder);
        if (zhifub != null) {
            AlipayTradeQueryResponse alipayTradeQueryResponse = ZhiFuBaoUtils.zfbPayQuery(zhifub.getTradeNo(), dept.getZfbToken());
            if (alipayTradeQueryResponse == null) {
                return Result.error("查询失败！没有交易记录！");
            }
            if (alipayTradeQueryResponse.getTradeStatus().equals("TRADE_SUCCESS")){
                payOrder.setPayTime(new Date());
                payOrder.setPayStatus("2");
                payOrder.setTransactionId(zhifub.getTradeNo());
                payOrder.setPayType("Alipay");
                this.updateById(payOrder);
                //用户余额处理
                Result<?> balance = this.balance(payDto);
                if (balance.getCode() != 200) {
                    return Result.error(606, balance.getMessage());
                }
                return Result.ok("支付成功！");
            }
            if (alipayTradeQueryResponse.getTradeStatus().equals("WAIT_BUYER_PAY")){
                Thread.sleep(20000);
                AlipayTradeQueryResponse zfbQuery = ZhiFuBaoUtils.zfbPayQuery(zhifub.getTradeNo(), dept.getZfbToken());
                if (zfbQuery.getTradeStatus().equals("TRADE_SUCCESS")){
                    payOrder.setPayTime(new Date());
                    payOrder.setPayStatus("2");
                    payOrder.setTransactionId(zhifub.getTradeNo());
                    payOrder.setPayType("Alipay");
                    this.updateById(payOrder);
                    //用户余额处理
                    Result<?> balance = this.balance(payDto);
                    if (balance.getCode() != 200) {
                        return Result.error(606, balance.getMessage());
                    }
                    return Result.OK("支付成功！");
                }
            }

        }
        return Result.error(606,"支付失败，请核实支付方式！");
    }


    /**
     * 调用微信支付（服务商）
     *
     * @param payDto
     * @param orderId
     * @return
     */
    @SneakyThrows
    @Override
    public Map<String, String> servicePayOrder(MerchantPay merchantPay, PayDto payDto, PayOrder payOrder, Integer orderId) {
        //微信支付的单位是分，要转换一下
        String amount = String.valueOf(payDto.getPayPrice().multiply(BigDecimal.valueOf(100)).intValue());
        //生成随机数
        String nonceStr = WXPayUtil.generateNonceStr();
        PayValues payValues = new PayValues();

        payValues.setAppid(PayConstants.App_ID_SERVICE);
        payValues.setMchId(PayConstants.MCH_ID_SERVICE);
        payValues.setKey(PayConstants.API_V2KEY_SERVICE);
        //格式化返回数据
        MyConfig config = new MyConfig(payValues);
        WXPay wxPay = new WXPay(config);
        SortedMap<String, String> jsonParam = new TreeMap<>();

//        1302752201
        jsonParam.put("sub_mch_id", merchantPay.getSpecialSubMerchants().trim());
//        if (payDto.getOrderType() == 3) {
//            jsonParam.put("profit_sharing", "Y");
//        }
        jsonParam.put("nonce_str", nonceStr);
        if (payDto.getOrderType() == 6) {
            String collect = payDto.getShopRecordList().stream().map(SmtMerchantShopRecord::getShopName).collect(Collectors.joining(","));
            jsonParam.put("body", collect);
        } else jsonParam.put("body", payOrder.getTrkName());
        jsonParam.put("out_trade_no", String.valueOf(orderId));
        jsonParam.put("total_fee", amount);
        String[] split = payDto.getSpbillCreateIp().split(",");
        jsonParam.put("spbill_create_ip", split[0]);
        jsonParam.put("auth_code", payDto.getAuthCode());
        //生成签名

        String sign = WXPayUtil.generateSignature(jsonParam, PayConstants.API_V2KEY_SERVICE);
        jsonParam.put("sign", sign);

        Map<String, String> result = wxPay.microPay(jsonParam);
        return result;
    }

    /**
     * 查询支付订单状态(商家)
     *
     * @return
     */
    @SneakyThrows
    @Override
    public Result<?> queryOrder(PayDto payDto, Integer outTradeNo) {
        //根据商家id查询商家配置的支付信息
        QueryWrapper<MerchantPay> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("merchant_id", payDto.getMerId());
        MerchantPay merchantPay = merchantPayService.getOne(queryWrapper);

        //生成随机数
        String nonceStr = WXPayUtil.generateNonceStr();
        //格式化返回数据
        PayValues payValues = new PayValues();

        payValues.setAppid(PayConstants.App_ID_SERVICE);
        payValues.setMchId(PayConstants.MCH_ID_SERVICE);
        payValues.setKey(PayConstants.API_V2KEY_SERVICE);


        //格式化返回数据
        MyConfig config = new MyConfig(payValues);
        WXPay wxPay = new WXPay(config);
        SortedMap<String, String> jsonParams = new TreeMap<>();


        jsonParams.put("sub_mch_id", merchantPay.getSpecialSubMerchants());
        jsonParams.put("nonce_str", nonceStr);
        jsonParams.put("out_trade_no", String.valueOf(outTradeNo));
        //生成签名
        String sign = WXPayUtil.generateSignature(jsonParams, PayConstants.API_V2KEY_SERVICE);
        jsonParams.put("sign", sign);
        //接收返回参数
        Map<String, String> result = wxPay.orderQuery(jsonParams);
        if (result.get("result_code").equals("SUCCESS") && result.get("return_code").equals("SUCCESS") && result.get("trade_state").equals("SUCCESS")) {
            PayOrder payOrder = this.getById(outTradeNo);
            //更新订单状态
            payOrder.setPayTime(new Date());
            payOrder.setPayStatus("2");
            payOrder.setTransactionId(result.get("transaction_id"));
            payOrder.setPayType("WeChat");
            this.updateById(payOrder);

            //用户余额处理
            Result<?> balance = this.balance(payDto);
            if (balance.getCode() != 200) {
                return Result.error(606, balance.getMessage());
            }
            return Result.OK("支付成功！");
        }
        return Result.error(606, result.get("trade_state_desc"));
    }

    /**
     * 查询支付订单状态（服务商）
     *
     * @return
     */
    @SneakyThrows
    @Override
    public Result<?> queryServiceOrder(PayDto payDto, Integer outTradeNo) {
        //根据商家id查询商家的商户号
        QueryWrapper<MerchantPay> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("merchant_id", payDto.getMerId());
        MerchantPay merchantPay = merchantPayService.getOne(queryWrapper);

        //生成随机数
        String nonceStr = WXPayUtil.generateNonceStr();
        //格式化返回数据
//        MyConfig config = new MyConfig();
//        WXPay wxPay = new WXPay(config);
        SortedMap<String, String> jsonParams = new TreeMap<>();
        jsonParams.put("appid", PayConstants.App_ID_SERVICE);
        jsonParams.put("mch_id", PayConstants.MCH_ID_SERVICE);
        jsonParams.put("sub_mch_id", merchantPay.getMchId());
        jsonParams.put("nonce_str", nonceStr);
        jsonParams.put("out_trade_no", String.valueOf(outTradeNo));
        //生成签名
        String sign = WXPayUtil.generateSignature(jsonParams, merchantPay.getApiKey());
        jsonParams.put("sign", sign);
        //接收返回参数
//        Map<String, String> result = wxPay.orderQuery(jsonParams);
//        if (result.get("result_code").equals("SUCCESS") && result.get("return_code").equals("SUCCESS") && result.get("trade_state").equals("SUCCESS")) {
//            PayOrder payOrder = this.getById(outTradeNo);
//            //更新订单状态
//            payOrder.setPayTime(new Date());
//            payOrder.setPayStatus("2");
//            payOrder.setTransactionId(result.get("transaction_id"));
//            payOrder.setPayType("WeChat");
//            this.updateById(payOrder);
//
//            //用户余额处理
//            Result<?> balance = this.balance(payDto);
//            if (balance.getCode() != 200) {
//                return Result.error(606, balance.getMessage());
//            }
//            return Result.OK("支付成功！");
//        }
//        return Result.error(606, result.get("trade_state_desc"));
        return null;
    }


    /**
     * 支付时用户余额逻辑处理以及不同订单类型的逻辑处理
     *
     * @param payDto
     */
    public Result<?> balance(PayDto payDto) {
//        YxUser yxUser = new YxUser();
//        BeanUtils.copyProperties(payDto, yxUser);
//        yxUser.setNowMoney(payDto.getBalancePay());
//        yxUser.setIntegral(payDto.getIntegral());
        //判断是否为余额支付 是的话需要扣除用户余额
        //判断是否为储值卡支付 是的话需要扣除用储值卡余额
        if (!payDto.getBalancePay().equals(BigDecimal.ZERO)) {
//            Result<?> subBalance = mallHelloApi.subBalance(yxUser);
            Boolean aBoolean = smtStoredUserPointService.subPrice(payDto.getBalancePay(), BigDecimal.ZERO, 2, payDto.getUid(), payDto.getMerId(), payDto.getOrderCouponNo());
//            余额支付
//            if (subBalance.getCode() != 200) {
//                return Result.error(subBalance.getCode(), subBalance.getMessage());
//        }
            //用户卡点
            if (aBoolean.equals(Boolean.FALSE)) {
                return Result.error(606, "点卡不足");
            }

        }

        //判断当前订单类型 不同类型做不同的逻辑处理
        if (payDto.getOrderType() == 1) {
//            yxUser.setTotalPrice(payDto.getTotalPrice().add(payDto.getGivePrice()));
//            yxUser.setIntegral(payDto.getIntegral());
//            //更新用户余额
//            mallHelloApi.updateAmount(yxUser);
            //更新用户储值卡金额
            Boolean aBoolean = smtStoredUserPointService.addPrice(payDto.getTotalPrice(), payDto.getGivePrice(), 1, payDto.getUid(), payDto.getMerId(), payDto.getOrderCouponNo());
            if (aBoolean.equals(Boolean.FALSE)) {
                return Result.error(606, "储值卡信息不存在");
            }
        } else if (payDto.getOrderType() == 3 && payDto.getYuYueId() != null) {
            SmtYuyueList yuyueList = yuyueListService.getById(payDto.getYuYueId());
            if (payDto.getCount() > (yuyueList.getCount() - yuyueList.getNum())) {
                return Result.error(606, "当前排期人数已满，请选择其他排期！");
            }
            Integer num = yuyueList.getNum() + payDto.getCount();
            yuyueList.setNum(num);
            yuyueListService.updateById(yuyueList);
            payDto.setOrd(yuyueList.getOrd());
            payDto.setQrCode(yuyueList.getQrCode());
            //保存收银台玩家信息与排期关联
            yuyueUserService.saveUser(payDto);
        }
//        if (payDto.getIsCoupon() != null && payDto.getIsCoupon().equals(0)) {
//            mallHelloApi.editCouponUser(payDto.getCouponId(), payDto.getOrderCouponNo());
//        }
        return Result.OK();
    }

    /**
     * 退款时处理订单逻辑
     *
     * @param refundRecord
     * @return
     */
    @Override
    public Result<?> updateOrder(RefundRecord refundRecord) {
        //逻辑处理 修改退款订单状态
        PayOrder payOrder = this.getById(refundRecord.getOutTradeNo());

        PayOrder order = new PayOrder();
        //退款金额转换为元
        order.setId(payOrder.getId());
        order.setRefundId(refundRecord.getId());
        order.setRefundTime(new Date());
        order.setPayStatus("3");
        order.setRefundFee(refundRecord.getRefundFee());
        this.updateById(order);

        //如果有余额支付则退回余额
        if (payOrder.getBalancePay().compareTo(BigDecimal.valueOf(0)) > 0) {
//            YxUser yxUser = new YxUser();
//            yxUser.setUid(payOrder.getUserId());
//            yxUser.setRefundBalance(payOrder.getBalancePay());
//            mallHelloApi.updateAmount(yxUser);
            Boolean aBoolean = smtStoredUserPointService.addPrice(payOrder.getBalancePay(), BigDecimal.ZERO, 2, payOrder.getUserId(), payOrder.getMerchantId(), payOrder.getOrderNo());
            if (aBoolean.equals(Boolean.FALSE)) {
                return Result.error(606, "储值卡信息不存在");
            }
        }

        //判断订单为跃动商品订单时需要将排期占的位置去除掉
        if (payOrder.getYuyueId() != null) {
            //根据订单选择的排期id查询排期
            SmtYuyueList yuyueList = yuyueListService.getById(payOrder.getYuyueId());
            //减掉占位
            Integer num = yuyueList.getNum() - payOrder.getCount();
            yuyueList.setNum(num);
            yuyueListService.updateById(yuyueList);
            //根据预约id查询对应的玩家并修改状态
            smtYuyueUserMapper.updateStatus(payOrder.getYuyueId(), payOrder.getCount(), payOrder.getUserId(), payOrder.getOrderNo());
        }

        //判断订单为充次订单时删除充次记录
        if (payOrder.getOrderType() == 2) {
            QueryWrapper<SmtOnceCardUsers> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", refundRecord.getOutTradeNo());
            smtOnceCardUsersService.remove(queryWrapper);
        }

        //判断订单为商家商品订单时修改状态
        if (payOrder.getOrderType() == 6 || payOrder.getOrderType().equals(3)) {
            smtMerchantShopRecordService.updateShopRecord(refundRecord.getOutTradeNo());
        }
        //判断优惠券 把已使用修改成未使用
        if (payOrder.getIsCoupon() != null && payOrder.getIsCoupon().equals(0)) {
            mallHelloApi.editCouponUser(0, payOrder.getOrderNo());
        }

        return Result.OK("退款成功!");
    }

    /**
     * 次卡充值逻辑处理
     *
     * @param payDto
     * @param orderId
     */
    @Override
    public void card(PayDto payDto, Integer orderId) {
        payDto.getCardUsers().stream().forEach(smtOnceCardUsers -> {
            smtOnceCardUsers.setUserId(payDto.getUid());
            smtOnceCardUsers.setUserNickname(payDto.getRealName());
            smtOnceCardUsers.setOrderId(orderId);
            smtOnceCardUsers.setMerchantId(Integer.valueOf(payDto.getMerId()));
            smtOnceCardUsers.setCardRest(smtOnceCardUsers.getProductNum() * smtOnceCardUsers.getCardRest());
            smtOnceCardUsers.setCardTotal(Long.valueOf(smtOnceCardUsers.getCardRest()));
            smtOnceCardUsersService.save(smtOnceCardUsers);
        });
    }

    /**
     * 商家商品逻辑处理
     *
     * @param payDto
     * @param orderId
     */
    @Override
    public void merchantShop(PayDto payDto, Integer orderId) {
        payDto.getShopRecordList().stream().forEach(shopRecord -> {
            //库存销量修改
            ProductNumDto productNumDto = new ProductNumDto();
            productNumDto.setProductId(shopRecord.getProductId());
            productNumDto.setNum(shopRecord.getBuyNum());
            productNumDto.setProductType(shopRecord.getProductType());
            productNumDto.setOrderPayType(1);
            productNumDto.setMerStoreId(shopRecord.getMerStoreId());
            productNumDto.setSkuId(shopRecord.getSkuId());
            mallHelloApi.updateNum(productNumDto);
            //添加商品订单关联信息
            shopRecord.setUserId(payDto.getUid());
            shopRecord.setOrderId(orderId);
            smtMerchantShopRecordService.save(shopRecord);
        });
    }


    /**
     * 商家商品逻辑处理
     *
     * @param payDto
     */
    @Override
    public Boolean checkMerShop(PayDto payDto) {
        AtomicReference<Boolean> aaa = new AtomicReference<>(Boolean.TRUE);
        payDto.getShopRecordList().stream().forEach(shopRecord -> {
            //库存销量修改
            ProductNumDto productNumDto = new ProductNumDto();
            productNumDto.setProductId(shopRecord.getProductId());
            productNumDto.setNum(shopRecord.getBuyNum());
            productNumDto.setProductType(shopRecord.getProductType());
            productNumDto.setMerStoreId(shopRecord.getMerStoreId());
            productNumDto.setOrderPayType(1);
            productNumDto.setSkuId(shopRecord.getSkuId());
            final Boolean aBoolean = mallHelloApi.checkNum(productNumDto);
            if (aBoolean.equals(Boolean.FALSE)) {
                aaa.set(Boolean.FALSE);
            }
        });
        return aaa.get();
    }


    /**
     * 根据订单状态保存订单
     *
     * @param payDto
     * @return
     */
    @Override
    public Result<?> saveOrderByOrderType(PayDto payDto, PayOrder payOrder) {
        //判断是否为现金支付是的话则不走支付
        if (!payDto.getCashPay().equals(BigDecimal.ZERO) && payDto.getPayPrice().equals(BigDecimal.ZERO) && payDto.getBalancePay().equals(BigDecimal.ZERO)) {
            payOrder.setPayStatus("2");
            payOrder.setPayType("cash");
            payOrder.setPayTime(new Date());
            //用户余额处理
            Result<?> balance = this.balance(payDto);
            if (balance.getCode() != 200) {
                return Result.error(606, balance.getMessage());
            }
            this.save(payOrder);
            //如果是充次订单则走此逻辑
            if (payDto.getOrderType() == 2) {
                this.card(payDto, payOrder.getId());
            }
            //如果是商家商品订单则走此逻辑
            if (payDto.getOrderType() == 6) {
                this.merchantShop(payDto, payOrder.getId());
            }
            //跃动商品判断
            if (payDto.getOrderType() == 3 && payDto.getShopRecordList() != null) {
                if (payDto.getYuYueId() == null) {
                    payOrder.setPayStatus("5");
                    this.updateById(payOrder);
                }
                this.merchantShop(payDto, payOrder.getId());
            }

            return Result.OK("现金支付成功");
        }

        //判断是否为余额支付是的话则不走支付
        if (!payDto.getBalancePay().equals(BigDecimal.ZERO) && payDto.getPayPrice().equals(BigDecimal.ZERO) && payDto.getCashPay().equals(BigDecimal.ZERO)) {
            payOrder.setPayStatus("2");
            payOrder.setPayType("ValueCard");
            payOrder.setPayTime(new Date());
            //用户余额处理
            Result<?> balance = this.balance(payDto);
            if (balance.getCode() != 200) {
                return Result.error(606, balance.getMessage());
            }
            this.save(payOrder);
            //如果是充次订单则走此逻辑
            if (payDto.getOrderType() == 2) {
                this.card(payDto, payOrder.getId());
            }
            //如果是商家商品订单则走此逻辑
            if (payDto.getOrderType() == 6) {
                this.merchantShop(payDto, payOrder.getId());
            }
            //跃动商品判断
            if (payDto.getOrderType() == 3 && payDto.getShopRecordList() != null) {
                if (payDto.getYuYueId() == null) {
                    payOrder.setPayStatus("5");
                    this.updateById(payOrder);
                }
                this.merchantShop(payDto, payOrder.getId());
            }
            return Result.OK("余额支付成功");
        }

        //判断是否为余额和现金组合支付是的话则不走支付
        if (!payDto.getBalancePay().equals(BigDecimal.ZERO) && payDto.getPayPrice().equals(BigDecimal.ZERO) && !payDto.getCashPay().equals(BigDecimal.ZERO)) {
            payOrder.setPayStatus("2");
            payOrder.setPayType("ValueCard&cash");
            payOrder.setPayTime(new Date());
            //用户余额处理
            Result<?> balance = this.balance(payDto);
            if (balance.getCode() != 200) {
                return Result.error(606, balance.getMessage());
            }
            this.save(payOrder);
            //如果是充次订单则走此逻辑
            if (payDto.getOrderType() == 2) {
                this.card(payDto, payOrder.getId());
            }
            //如果是商家商品订单则走此逻辑
            if (payDto.getOrderType() == 6) {
                this.merchantShop(payDto, payOrder.getId());
            }
            //跃动商品判断
            if (payDto.getOrderType() == 3 && payDto.getShopRecordList() != null) {
                if (payDto.getYuYueId() == null) {
                    payOrder.setPayStatus("5");
                    this.updateById(payOrder);
                }
                this.merchantShop(payDto, payOrder.getId());
            }
            return Result.OK("余额现金组合支付成功");
        }
        //如果付金额为零
        if (payDto.getTotalPrice().equals(BigDecimal.ZERO)) {
            //如果在回复金额为0
            payOrder.setPayStatus("2");
            payOrder.setPayType("零元支付");
            payOrder.setPayTime(new Date());
            //用户余额处理
            Result<?> balance = this.balance(payDto);
            if (balance.getCode() != 200) {
                return Result.error(606, balance.getMessage());
            }
            this.save(payOrder);
            //如果是充次订单则走此逻辑
            if (payDto.getOrderType() == 2) {
                this.card(payDto, payOrder.getId());
            }
            //如果是商家商品订单则走此逻辑
            if (payDto.getOrderType() == 6) {
                this.merchantShop(payDto, payOrder.getId());
            }
            //跃动商品判断
            if (payDto.getOrderType() == 3 && payDto.getShopRecordList() != null) {
                if (payDto.getYuYueId() == null) {
                    payOrder.setPayStatus("5");
                    this.updateById(payOrder);
                }
                this.merchantShop(payDto, payOrder.getId());
            }
            return Result.OK("订单零元支付");

        }
        return Result.error(608, "未匹配到订单！");
    }

    /**
     * 用户信息返回
     *
     * @param payOrderList
     * @return
     */
    @Override
    public List<PayOrder> queryUserdetails(List<PayOrder> payOrderList, String merId) {
        //获取用户的信息
        payOrderList.forEach(payOrder1 -> {
            if (payOrder1.getUserId() != null) {
                YxUser yxUser = mallHelloApi.queryUser(payOrder1.getUserId());
                if (yxUser != null) {
                    //获取用户等级 以及信息
                    payOrder1.setUsername(yxUser.getRealName());
                    payOrder1.setPhone(yxUser.getPhone());
                    payOrder1.setNickName(yxUser.getNickname());
                    YxSystemUserLevel yxSystemUserLevel = mallHelloApi.queryLevel(yxUser.getLevel());
                    if (yxSystemUserLevel != null) {
                        payOrder1.setLevel(yxSystemUserLevel.getGrade());
                        payOrder1.setLevelName(yxSystemUserLevel.getName());
                    }
                }
                YxStoreCouponUser yxStoreCouponUser = mallHelloApi.queryByOrderNo(payOrder1.getOrderNo());
                if (yxStoreCouponUser != null) {
                    CouponUserVo couponUserVo = new CouponUserVo();
                    BeanUtils.copyProperties(yxStoreCouponUser, couponUserVo);
                    payOrder1.setCouponUserVo(couponUserVo);
                }
            } else {
                payOrder1.setUsername("散客");
            }
        });

        return payOrderList;
    }


    public Result<?> orderByOrderType(PayDto payDto, PayOrder payOrder) {
        //判断是否为现金支付是的话则不走支付
        if (!payDto.getCashPay().equals(BigDecimal.ZERO) && payDto.getPayPrice().equals(BigDecimal.ZERO) && payDto.getBalancePay().equals(BigDecimal.ZERO)) {
            payOrder.setPayStatus("2");
            payOrder.setPayType("cash");
            payOrder.setPayTime(new Date());
            //用户余额处理
            Result<?> balance = this.balance(payDto);
            if (balance.getCode() != 200) {
                return Result.error(606, balance.getMessage());
            }
            this.updateById(payOrder);
            //跃动商品判断
            if (payDto.getOrderType() == 3 && payDto.getShopRecordList() != null) {
                if (payDto.getYuYueId() == null) {
                    payOrder.setPayStatus("5");
                    this.updateById(payOrder);
                }
            }
            return Result.OK("现金支付成功");
        }

        //判断是否为余额支付是的话则不走支付
        if (!payDto.getBalancePay().equals(BigDecimal.ZERO) && payDto.getPayPrice().equals(BigDecimal.ZERO) && payDto.getCashPay().equals(BigDecimal.ZERO)) {
            payOrder.setPayStatus("2");
            payOrder.setPayType("ValueCard");
            payOrder.setPayTime(new Date());
            //用户余额处理
            Result<?> balance = this.balance(payDto);
            if (balance.getCode() != 200) {
                return Result.error(606, balance.getMessage());
            }
            this.updateById(payOrder);
            //跃动商品判断
            if (payDto.getOrderType() == 3 && payDto.getShopRecordList() != null) {
                if (payDto.getYuYueId() == null) {
                    payOrder.setPayStatus("5");
                    this.updateById(payOrder);
                }
            }
            return Result.OK("余额支付成功");
        }

        //判断是否为余额和现金组合支付是的话则不走支付
        if (!payDto.getBalancePay().equals(BigDecimal.ZERO) && payDto.getPayPrice().equals(BigDecimal.ZERO) && !payDto.getCashPay().equals(BigDecimal.ZERO)) {
            payOrder.setPayStatus("2");
            payOrder.setPayType("ValueCard&cash");
            payOrder.setPayTime(new Date());
            //用户余额处理
            Result<?> balance = this.balance(payDto);
            if (balance.getCode() != 200) {
                return Result.error(606, balance.getMessage());
            }
            this.updateById(payOrder);
            //跃动商品判断
            if (payDto.getOrderType() == 3 && payDto.getShopRecordList() != null) {
                if (payDto.getYuYueId() == null) {
                    payOrder.setPayStatus("5");
                    this.updateById(payOrder);
                }
            }
            return Result.OK("余额现金组合支付成功");
        }
        //如果付金额为零
        if (payDto.getTotalPrice().equals(BigDecimal.ZERO)) {
            //如果在回复金额为0
            payOrder.setPayStatus("2");
            payOrder.setPayType("零元支付");
            payOrder.setPayTime(new Date());
            //用户余额处理
            Result<?> balance = this.balance(payDto);
            if (balance.getCode() != 200) {
                return Result.error(606, balance.getMessage());
            }
            this.updateById(payOrder);
            //跃动商品判断
            if (payDto.getOrderType() == 3 && payDto.getShopRecordList() != null) {
                if (payDto.getYuYueId() == null) {
                    payOrder.setPayStatus("5");
                }
            }
            return Result.OK("订单零元支付");

        }
        return Result.error(608, "未匹配到订单！");
    }

    /**
     * 多商户分账记录
     *
     * @param
     */
//    public void calcOrder() {
//        //1先初始化
//        initMecId();
//        //2筛选全部未分账的
//        LambdaQueryWrapper<PayOrder> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(PayOrder::getSplitType, 0);
//        lqw.in(PayOrder::getOrderType, new ArrayList<>(Arrays.asList(3, 4, 5, 7)));   //分账的类型: 3 商品 4 抖音 5美团 7 扣次订单  //不分账：1 储值 2 次卡 6 商家普通商品
//        lqw.eq(PayOrder::getPayStatus, 2);
//        List<PayOrder> payOrders = this.list(lqw);
//
//        //创建手续费用表
//        Map<String, List<PayOrder>> groupMap = payOrders.stream().collect(Collectors.groupingBy(PayOrder::getMerchantId));
//        for (Map.Entry<String, List<PayOrder>> entry : groupMap.entrySet()) {
//            String merId = entry.getKey();
//            List<PayOrder> payOrderList = entry.getValue();
//            //创建记录
//            SmtSplitRecord splitRecord = getSmtSplitRecord(0, merId);
//            splitRecord.setOrderIds(payOrderList.stream().map(a -> String.valueOf(a.getId())).collect(Collectors.joining(",")));
//            smtSplitRecordService.saveOrUpdate(splitRecord);
//            //获取键值
//
//            List<SmtSplitOrderFee> orderFees = new ArrayList<>();
//
//            List<PayOrder> allCashs = payOrderList.stream().filter(payOrder -> payOrder.getCashPay().compareTo(BigDecimal.ZERO) > 0).collect(Collectors.toList());
//            BigDecimal allCash = allCashs.stream().map(PayOrder::getCashPay).reduce(BigDecimal.ZERO, BigDecimal::add);
//            if (allCash.compareTo(BigDecimal.ZERO) > 0) {
//                SmtSplitOrderFee smtSplitOrderFee = new SmtSplitOrderFee();
//                dodo(smtSplitOrderFee, allCash, splitRecord.getId(), merId, allCashs, "cash");
//                smtSplitOrderFeeService.saveOrUpdate(smtSplitOrderFee);
//                orderFees.add(smtSplitOrderFee);
//                //修改关联orderPay
//                linkOrderPay(allCashs, splitRecord.getId(), smtSplitOrderFee.getId());
//            }
//
//            List<PayOrder> allWxs = payOrderList.stream().filter(payOrder -> payOrder.getPayType().contains("WeChat")).collect(Collectors.toList());
//            BigDecimal allWeixin = allWxs.stream().map(PayOrder::getPayPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
//            if (allWeixin.compareTo(BigDecimal.ZERO) > 0) {
//                SmtSplitOrderFee smtSplitOrderFee = new SmtSplitOrderFee();
//                dodo(smtSplitOrderFee, allWeixin, splitRecord.getId(), merId, allWxs, "WeChat");
//                smtSplitOrderFeeService.saveOrUpdate(smtSplitOrderFee);
//                orderFees.add(smtSplitOrderFee);
//                //修改关联orderPay
//                linkOrderPay(allWxs, splitRecord.getId(), smtSplitOrderFee.getId());
//            }
//
//            List<PayOrder> allZfb = payOrderList.stream().filter(payOrder -> payOrder.getPayType().contains("ZhiFuBao")).collect(Collectors.toList());
//            BigDecimal allZhifubao = allZfb.stream().map(PayOrder::getPayPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
//            if (allZhifubao.compareTo(BigDecimal.ZERO) > 0) {
//                SmtSplitOrderFee smtSplitOrderFee = new SmtSplitOrderFee();
//                dodo(smtSplitOrderFee, allZhifubao, splitRecord.getId(), merId, allZfb, "ZhiFuBao");
//                smtSplitOrderFeeService.saveOrUpdate(smtSplitOrderFee);
//                orderFees.add(smtSplitOrderFee);
//                //修改关联orderPay
//                linkOrderPay(allZfb, splitRecord.getId(), smtSplitOrderFee.getId());
//            }
//            //2 com
//            intoOrderCom(splitRecord, merId, orderFees);
//            //3 更新record
//            splitRecord.setOrderYstAmounts(allWeixin.add(allZhifubao));
//            splitRecord.setOrderCashAmounts(allCash);
//            splitRecord.setOrderAmounts(splitRecord.getOrderYstAmounts().add(splitRecord.getOrderCashAmounts()));
//            smtSplitRecordService.saveOrUpdate(splitRecord);
//        }
//
//    }
    public void calcOrder() {
        //1先初始化
        initMecId();
        //2筛选全部未分账的
        LambdaQueryWrapper<PayOrder> lqw = new LambdaQueryWrapper<>();
        lqw.eq(PayOrder::getSplitType, 0);
        lqw.in(PayOrder::getOrderType, new ArrayList<>(Arrays.asList(3, 4, 5, 7)));   //分账的类型: 3 商品 4 抖音 5美团 7 扣次订单  //不分账：1 储值 2 次卡 6 商家普通商品
        lqw.eq(PayOrder::getPayStatus, 2);
        List<PayOrder> payOrders = this.list(lqw);

        //创建手续费用表
        //需要改成根据类型orderType进行筛选  然后在根据类型进行删选门店   进行分账

        Map<String, List<PayOrder>> groupMap = payOrders.stream().collect(Collectors.groupingBy(PayOrder::getMerchantId));
        for (Map.Entry<String, List<PayOrder>> entry : groupMap.entrySet()) {
            String merId = entry.getKey();
            List<PayOrder> payOrderList = entry.getValue();
//            创建记录
            SmtSplitRecord splitRecord = getSmtSplitRecord(0, merId);
            splitRecord.setOrderIds(payOrderList.stream().map(a -> String.valueOf(a.getId())).collect(Collectors.joining(",")));
            smtSplitRecordService.saveOrUpdate(splitRecord);
            //汇总门店fee和com
            List<SmtSplitOrderFee> orderFees = new ArrayList<>();
            List<SmtSplitOrderCom> orderComs = new ArrayList<>();
            if (!CollectionUtils.isEmpty(payOrderList)) {
                //如果订单记录部位空     那么  进行记录
                payOrderList.forEach(pp -> {
                    List<SmtSplitOrderFee> orderFeeList = new ArrayList<>();
                    //现金
                    if (pp.getCashPay().compareTo(BigDecimal.ZERO) > 0) {
                        SmtSplitOrderFee smtSplitOrderFee = new SmtSplitOrderFee();
                        dodo(smtSplitOrderFee, pp.getCashPay(), splitRecord.getId(), merId, pp, "cash");
                        smtSplitOrderFeeService.saveOrUpdate(smtSplitOrderFee);
                        orderFeeList.add(smtSplitOrderFee);
                        orderFees.add(smtSplitOrderFee);
                        //修改关联orderPay
                        linkOrderPay(pp, splitRecord.getId(), smtSplitOrderFee.getId());
                    }
                    //余额
                    if (pp.getBalancePay().compareTo(BigDecimal.ZERO) > 0) {
                        SmtSplitOrderFee smtSplitOrderFee = new SmtSplitOrderFee();
                        dodo(smtSplitOrderFee, pp.getBalancePay(), splitRecord.getId(), merId, pp, "ValueCard");
                        smtSplitOrderFeeService.saveOrUpdate(smtSplitOrderFee);
                        orderFeeList.add(smtSplitOrderFee);
                        orderFees.add(smtSplitOrderFee);
                        //修改关联orderPay
                        linkOrderPay(pp, splitRecord.getId(), smtSplitOrderFee.getId());
                    }
                    //扫码支付
                    if (pp.getPayPrice().compareTo(BigDecimal.ZERO) > 0) {
                        SmtSplitOrderFee smtSplitOrderFee = new SmtSplitOrderFee();
                        dodo(smtSplitOrderFee, pp.getPayPrice(), splitRecord.getId(), merId, pp, "WeChat");
                        smtSplitOrderFeeService.saveOrUpdate(smtSplitOrderFee);
                        orderFeeList.add(smtSplitOrderFee);
                        orderFees.add(smtSplitOrderFee);
                        //修改关联orderPay
                        linkOrderPay(pp, splitRecord.getId(), smtSplitOrderFee.getId());
                    }
                    intoOrderComs(orderComs, merId, orderFeeList);
                });
            }
//           ----------进行记录-------
            inOrderRecord(splitRecord, orderFees, orderComs, payOrders);
        }

    }


    void inOrderRecord(SmtSplitRecord splitRecord, List<SmtSplitOrderFee> orderFees, List<SmtSplitOrderCom> orderComs, List<PayOrder> payOrders) {
        String orderComIds = orderComs.stream().map(a -> {
            return String.valueOf(a.getId());
        }).collect(Collectors.joining(","));
        splitRecord.setOrderComIds(orderComIds);
        //获取订单金额
        BigDecimal allWeixin = payOrders.stream().map(PayOrder::getPayPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal allCash = payOrders.stream().map(PayOrder::getCashPay).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal allBlance = payOrders.stream().map(PayOrder::getBalancePay).reduce(BigDecimal.ZERO, BigDecimal::add);
        splitRecord.setOrderYstAmounts(allWeixin);
        splitRecord.setOrderCashAmounts(allBlance.add(allCash));
        splitRecord.setOrderAmounts(splitRecord.getOrderYstAmounts().add(splitRecord.getOrderCashAmounts()));
        smtSplitRecordService.saveOrUpdate(splitRecord);
    }


//    /**
//     * 单商户
//     *
//     * @param merchantId
//     */
//    public void calcOrderMerchantId(String merchantId) {
//        //1先初始化
//        initMecId();
//        //2筛选全部未分账的
//        LambdaQueryWrapper<PayOrder> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(PayOrder::getSplitType, 0);
//        lqw.eq(PayOrder::getPayStatus, 2);
//        lqw.ne(PayOrder::getOrderType, 1);
//        lqw.eq(PayOrder::getMerchantId, merchantId);
////根据商户查询，
//        List<PayOrder> payOrders = this.list(lqw);
//
//
//        //-----------------------传商户id----------------------------------------------------
//        //1.根据门店chauxn
//
//        //创建记录
//        SmtSplitRecord splitRecord = getSmtSplitRecord(0, merchantId);
//        splitRecord.setOrderIds(payOrders.stream().map(a -> String.valueOf(a.getId())).collect(Collectors.joining(",")));
//        smtSplitRecordService.saveOrUpdate(splitRecord);
//        //获取键值
//
//        List<SmtSplitOrderFee> orderFees = new ArrayList<>();
//
//
//        List<PayOrder> allCashs = payOrders.stream().filter(payOrder -> payOrder.getCashPay().compareTo(BigDecimal.ZERO) > 0).collect(Collectors.toList());
//        BigDecimal allCash = allCashs.stream().map(PayOrder::getCashPay).reduce(BigDecimal.ZERO, BigDecimal::add);
//        if (allCash.compareTo(BigDecimal.ZERO) > 0) {
//            SmtSplitOrderFee smtSplitOrderFee = new SmtSplitOrderFee();
//            dodo(smtSplitOrderFee, allCash, splitRecord.getId(), merchantId, allCashs, "cash");
//            smtSplitOrderFeeService.saveOrUpdate(smtSplitOrderFee);
//            orderFees.add(smtSplitOrderFee);
//            //修改关联orderPay
//            linkOrderPay(allCashs, splitRecord.getId(), smtSplitOrderFee.getId());
//        }
//
//        List<PayOrder> allWxs = payOrders.stream().filter(payOrder -> payOrder.getPayType().contains("WeChat")).collect(Collectors.toList());
//        BigDecimal allWeixin = allWxs.stream().map(PayOrder::getPayPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
//        if (allWeixin.compareTo(BigDecimal.ZERO) > 0) {
//            SmtSplitOrderFee smtSplitOrderFee = new SmtSplitOrderFee();
//            dodo(smtSplitOrderFee, allWeixin, splitRecord.getId(), merchantId, allWxs, "WeChat");
//            smtSplitOrderFeeService.saveOrUpdate(smtSplitOrderFee);
//            orderFees.add(smtSplitOrderFee);
//            //修改关联orderPay
//            linkOrderPay(allWxs, splitRecord.getId(), smtSplitOrderFee.getId());
//        }
//
//        List<PayOrder> allZfb = payOrders.stream().filter(payOrder -> payOrder.getPayType().contains("ZhiFuBao")).collect(Collectors.toList());
//        BigDecimal allZhifubao = allZfb.stream().map(PayOrder::getPayPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
//        if (allZhifubao.compareTo(BigDecimal.ZERO) > 0) {
//            SmtSplitOrderFee smtSplitOrderFee = new SmtSplitOrderFee();
//            dodo(smtSplitOrderFee, allZhifubao, splitRecord.getId(), merchantId, allZfb, "ZhiFuBao");
//            smtSplitOrderFeeService.saveOrUpdate(smtSplitOrderFee);
//            orderFees.add(smtSplitOrderFee);
//            //修改关联orderPay
//            linkOrderPay(allZfb, splitRecord.getId(), smtSplitOrderFee.getId());
//        }
//        //2 com
//        intoOrderCom(splitRecord, merchantId, orderFees);
//        //3 更新record
//        splitRecord.setOrderYstAmounts(allWeixin.add(allZhifubao));
//        splitRecord.setOrderCashAmounts(allCash);
//        splitRecord.setOrderAmounts(splitRecord.getOrderYstAmounts().add(splitRecord.getOrderCashAmounts()));
//        smtSplitRecordService.saveOrUpdate(splitRecord);
//
//    }
//
//
//    /**
//     * 单商户
//     *
//     * @param recordId
//     */
//    public void calcOrderRecordId(Integer recordId) {
//        //1先初始化
//        initMecId();
//
//        SmtSplitRecord splitRecord = smtSplitRecordService.getById(recordId);
//        if (splitRecord != null) {
//            //2筛选全部未分账的
//            LambdaQueryWrapper<PayOrder> lqw = new LambdaQueryWrapper<>();
//            lqw.ne(PayOrder::getOrderType, 1);
//            lqw.eq(PayOrder::getSplitType, 0);
////根据商户查询，
//            String[] split = splitRecord.getOrderIds().split(",");
//            List<Integer> integerList = Arrays.asList(split).stream().map(s -> Integer.valueOf(s)).collect(Collectors.toList());
//            lqw.in(PayOrder::getId, integerList);
//            List<PayOrder> payOrders = this.list(lqw);
//
//
//            //-----------------------传商户id----------------------------------------------------
//            //1.根据门店chauxn
//            //创建记录
//
//            splitRecord.setOrderIds(payOrders.stream().map(a -> String.valueOf(a.getId())).collect(Collectors.joining(",")));
//            smtSplitRecordService.saveOrUpdate(splitRecord);
//            //获取键值
//            List<SmtSplitOrderFee> orderFees = new ArrayList<>();
//            List<PayOrder> allCashs = payOrders.stream().filter(payOrder -> payOrder.getCashPay().compareTo(BigDecimal.ZERO) > 0).collect(Collectors.toList());
//            BigDecimal allCash = allCashs.stream().map(PayOrder::getCashPay).reduce(BigDecimal.ZERO, BigDecimal::add);
//            if (allCash.compareTo(BigDecimal.ZERO) > 0) {
//                SmtSplitOrderFee smtSplitOrderFee = new SmtSplitOrderFee();
//                dodo(smtSplitOrderFee, allCash, splitRecord.getId(), splitRecord.getMerchantId(), allCashs, "cash");
//                smtSplitOrderFeeService.saveOrUpdate(smtSplitOrderFee);
//                orderFees.add(smtSplitOrderFee);
//                //修改关联orderPay
//                linkOrderPay(allCashs, splitRecord.getId(), smtSplitOrderFee.getId());
//            }
//
//            List<PayOrder> allWxs = payOrders.stream().filter(payOrder -> payOrder.getPayType().contains("WeChat")).collect(Collectors.toList());
//            BigDecimal allWeixin = allWxs.stream().map(PayOrder::getPayPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
//            if (allWeixin.compareTo(BigDecimal.ZERO) > 0) {
//                SmtSplitOrderFee smtSplitOrderFee = new SmtSplitOrderFee();
//                dodo(smtSplitOrderFee, allWeixin, splitRecord.getId(), splitRecord.getMerchantId(), allWxs, "WeChat");
//                smtSplitOrderFeeService.saveOrUpdate(smtSplitOrderFee);
//                orderFees.add(smtSplitOrderFee);
//                //修改关联orderPay
//                linkOrderPay(allWxs, splitRecord.getId(), smtSplitOrderFee.getId());
//            }
//
//            List<PayOrder> allZfb = payOrders.stream().filter(payOrder -> payOrder.getPayType().contains("ZhiFuBao")).collect(Collectors.toList());
//            BigDecimal allZhifubao = allZfb.stream().map(PayOrder::getPayPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
//            if (allZhifubao.compareTo(BigDecimal.ZERO) > 0) {
//                SmtSplitOrderFee smtSplitOrderFee = new SmtSplitOrderFee();
//                dodo(smtSplitOrderFee, allZhifubao, splitRecord.getId(), splitRecord.getMerchantId(), allZfb, "ZhiFuBao");
//                smtSplitOrderFeeService.saveOrUpdate(smtSplitOrderFee);
//                orderFees.add(smtSplitOrderFee);
//                //修改关联orderPay
//                linkOrderPay(allZfb, splitRecord.getId(), smtSplitOrderFee.getId());
//            }
//            //2 com
//            intoOrderCom(splitRecord, splitRecord.getMerchantId(), orderFees);
//            //3 更新record
//            splitRecord.setOrderYstAmounts(allWeixin.add(allZhifubao));
//            splitRecord.setOrderCashAmounts(allCash);
//            splitRecord.setOrderAmounts(splitRecord.getOrderYstAmounts().add(splitRecord.getOrderCashAmounts()));
//            smtSplitRecordService.saveOrUpdate(splitRecord);
//        }
//    }

    @Override
    public List<SmtSplitMerchant> dailyMerchant(String merchantId, String startTime, String endTime) {
        initMecId();
        //2筛选全部未分账的
        LambdaQueryWrapper<PayOrder> lqw = new LambdaQueryWrapper<>();
        lqw.eq(PayOrder::getPayStatus, 2);
        if (StringUtils.isNoneBlank(merchantId)) {
            lqw.eq(PayOrder::getMerchantId, merchantId);
        }
        lqw.apply("DATE(create_time) <= '" + endTime + "'");
        lqw.apply("DATE(create_time) >= '" + startTime + "'");
        //根据商户查询，
        List<PayOrder> payOrders = this.list(lqw);
        List<SmtSplitMerchant> splitMerchantArrayList = new ArrayList<>();
        Map<String, List<PayOrder>> groupMap = payOrders.stream().collect(Collectors.groupingBy(PayOrder::getMerchantId));
        for (Map.Entry<String, List<PayOrder>> entry : groupMap.entrySet()) {
            String merId = entry.getKey();
            List<PayOrder> payOrderList = entry.getValue();
            //总营业额
            BigDecimal actualPriceMer = payOrderList.stream().map(PayOrder::getActualPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
            //充值未分配金额
            BigDecimal actualValuePriceMer = payOrderList.stream().filter(payOrder -> payOrder.getOrderType() == 1 && payOrder.getSplitType() == 0).map(PayOrder::getActualPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
            //获取充值后的消费记录
            BigDecimal BalancePriceMer = payOrderList.stream().map(PayOrder::getBalancePay).reduce(BigDecimal.ZERO, BigDecimal::add);
            //填写日报表
            SmtSplitMerchant smtSplitMerchant = new SmtSplitMerchant();
            smtSplitMerchant.setMerchantId(merId);
            smtSplitMerchant.setAmountSum(actualPriceMer);
            smtSplitMerchant.setAmountLock(actualPriceMer.subtract(BalancePriceMer));
            //获取用户门店当天分账的金额
            List<SmtSplitOrderCom> splitOrderComs = smtSplitOrderComService.querySplitPrice(merId, startTime, endTime);
            //分账总金额
            BigDecimal reciveAmounts = splitOrderComs.stream().map(SmtSplitOrderCom::getReciveAmounts).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal reciveTsyAmounts = splitOrderComs.stream().filter(smtSplitOrderCom -> smtSplitOrderCom.getSplitType().equals("TSY")).map(SmtSplitOrderCom::getReciveAmounts).reduce(BigDecimal.ZERO, BigDecimal::add);

            //获取门店获取分账金额
            BigDecimal amountSplitHave = splitOrderComs.stream().filter(smtSplitOrderCom -> smtSplitOrderCom.getComType().equals(0)).map(SmtSplitOrderCom::getReciveAmounts).reduce(BigDecimal.ZERO, BigDecimal::add);
            //获取门店通商云获取金额
            BigDecimal amountTsySplitHave = splitOrderComs.stream().filter(smtSplitOrderCom -> smtSplitOrderCom.getComType().equals(0) && smtSplitOrderCom.getSplitType().equals("TSY")).map(SmtSplitOrderCom::getReciveAmounts).reduce(BigDecimal.ZERO, BigDecimal::add);
            smtSplitMerchant.setAmountSplit(reciveAmounts);
            smtSplitMerchant.setAmountSplitHave(amountSplitHave);
            smtSplitMerchant.setAmountTsySplitHave(amountTsySplitHave);
            smtSplitMerchant.setAmountTsySplit(reciveTsyAmounts);
            Dept dept = upmsHelloApi.queryByDept(Long.valueOf(merId));
            smtSplitMerchant.setMerName(dept.getName());
            if (StringUtils.isNoneBlank(merchantId)) {
                smtSplitMerchant.setSplitMerType(1);
            }
            splitMerchantArrayList.add(smtSplitMerchant);
        }
        smtSplitMerchantService.saveBatch(splitMerchantArrayList);
        return splitMerchantArrayList;
    }


//    private void linkOrderPay(List<PayOrder> payOrderList, Integer recordId, Integer orderFeeId) {
//        payOrderList.stream().peek(a -> {
//            a.setSplitType(1);
//            a.setRecordId(recordId);
//            a.setRecordFeeIds(Strings.isNullOrEmpty(a.getRecordFeeIds()) ? String.valueOf(orderFeeId) : a.getRecordFeeIds() + "," + orderFeeId);
//        }).collect(Collectors.toList());
//        this.updateBatchById(payOrderList);
//    }


    private void linkOrderPay(PayOrder payOrder, Integer recordId, Integer orderFeeId) {
        payOrder.setSplitType(1);
        payOrder.setRecordId(recordId);
        payOrder.setRecordFeeIds(String.valueOf(orderFeeId));
        this.updateById(payOrder);
    }


    private void intoOrderComs(List<SmtSplitOrderCom> orderComs, String merId, List<SmtSplitOrderFee> orderFees) {
        List<SmtSplitOrderCom> orderComList = new ArrayList<>();
//        step1：汇总orderFees得到全部可分配金额——区分那些是分配，那些部分怕
        List<SmtSplitRuleCom> ruleComs = smtSplitRuleComService.queryComList(merId);

        //得到所有可分配金额
        Map<String, List<SmtSplitOrderFee>> groupMap = orderFees.stream().collect(Collectors.groupingBy(SmtSplitOrderFee::getPayType));
        for (Map.Entry<String, List<SmtSplitOrderFee>> entry : groupMap.entrySet()) {
            String payType = entry.getKey();
            List<SmtSplitOrderFee> smtSplitOrderFeeList = entry.getValue();
            if (smtSplitOrderFeeList == null || smtSplitOrderFeeList.size() == 0) continue;

            SmtSplitOrderFee curOrderFee = smtSplitOrderFeeList.get(0);
            String merName = curOrderFee.getMerName();

            BigDecimal allSplit = smtSplitOrderFeeList.stream().map(SmtSplitOrderFee::getSplitAmounts).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal orderAmount = smtSplitOrderFeeList.stream().map(SmtSplitOrderFee::getOrderAmounts).reduce(BigDecimal.ZERO, BigDecimal::add);
            ruleComs.forEach(cc -> {
                SmtSplitOrderCom orderCom = new SmtSplitOrderCom();
                orderCom.setMerchantId(merId);
                orderCom.setMerName(merName);
                orderCom.setComId(cc.getComId());
                orderCom.setComType(cc.getComType());
                orderCom.setComName(cc.getComName());
                orderCom.setSplitAccount(cc.getAccount());
                orderCom.setSubMchid(cc.getSubMchid());
                //获取订单id
                orderCom.setOrderId(smtSplitOrderFeeList.get(0).getOrderIds());
                orderCom.setType(cc.getType());
                orderCom.setRelationType(cc.getRelationType());
                BigDecimal havPays = allSplit.multiply(cc.getAccount()).setScale(2, 4);
                orderComsAdd(orderCom, 0, allSplit, havPays, payType, orderAmount);
                orderComList.add(orderCom);
                orderComs.add(orderCom);
            });

            BigDecimal allFee = smtSplitOrderFeeList.stream().map(SmtSplitOrderFee::getFeeAmounts).reduce(BigDecimal.ZERO, BigDecimal::add);
            SmtSplitOrderCom orderCom2 = new SmtSplitOrderCom();
            orderCom2.setMerchantId(merId);
            orderCom2.setMerName(merName);
            //需要创建平台账号
            orderCom2.setComId("1");
            orderCom2.setComType("3");
            orderCom2.setComName("意想意创");
            orderCom2.setSplitAccount(new BigDecimal(1));
            orderComsAdd(orderCom2, 1, allFee, allFee, payType, orderAmount);
            orderComList.add(orderCom2);
            orderComs.add(orderCom2);
        }
        smtSplitOrderComService.saveOrUpdateBatch(orderComList);


        //订单是扫码支付走此逻辑    再次进行调用第三方分账接口
        payOrderPrice(orderComList);
    }


    void payOrderPrice(List<SmtSplitOrderCom> orderComList) {
        List<SmtSplitOrderCom> weChat = orderComList.stream().filter(aa -> aa.getSplitType().equals("WeChat")).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(weChat)) {
            Map<String, List<SmtSplitOrderCom>> groupMap = weChat.stream().collect(Collectors.groupingBy(SmtSplitOrderCom::getOrderId));
            for (Map.Entry<String, List<SmtSplitOrderCom>> entry : groupMap.entrySet()) {
                String orderId = entry.getKey();
                List<SmtSplitOrderCom> smtSplitOrderCom = entry.getValue();
                PayOrder payOrder = this.getById(Integer.valueOf(orderId));
                ProfitSharingDto profitSharingDto = new ProfitSharingDto();
                profitSharingDto.setReceiverList(smtSplitOrderCom);
                JSONObject sharing = ProfitUtil.sharing(profitSharingDto, payOrder, smtSplitOrderCom.get(0).getSubMchid());
                //获取每一个分账接收方对应的结果
                List<ProfitVo> profitVos = sharing.getJSONArray("receivers").stream().map(item -> JSON.parseObject(((JSONObject) item).toString(), ProfitVo.class)).collect(Collectors.toList());
                profitVos.forEach(profitVo -> {
                    SmtSharingMember member = new SmtSharingMember();
                    member.setTransactionId(sharing.getString("transaction_id"));
                    member.setOutOrderNo(sharing.getString("out_order_no"));
                    member.setSubMchid(sharing.getString("sub_mchid"));
                    member.setOrderId(sharing.getString("order_id"));
                    member.setAccount(profitVo.getAccount());
                    member.setAmount(profitVo.getAmount());
                    member.setState(profitVo.getResult());
                    member.setDescription(profitVo.getDescription());
                    //失败的时候才会返回
                    member.setFailReason(profitVo.getFailReason());
                    member.setType(profitVo.getType());
                    member.setDetailId(profitVo.getDetailId());
                    member.setFinishTime(profitVo.getFinishTime());
                    smtSharingMemberService.save(member);
                });
            }
        }
    }

//    private void intoOrderCom(SmtSplitRecord splitRecord, String merId, List<SmtSplitOrderFee> orderFees) {
//        List<SmtSplitOrderCom> orderComs = new ArrayList<>();
////        step1：汇总orderFees得到全部可分配金额——区分那些是分配，那些部分怕
//        List<SmtSplitRuleCom> ruleComs = smtSplitRuleComService.queryComList(merId);
//
//        //得到所有可分配金额
//        BigDecimal reduce = orderFees.stream().map(SmtSplitOrderFee::getSplitAmounts).reduce(BigDecimal.ZERO, BigDecimal::add);
//        splitRecord.setSplitYstAmounts(BigDecimal.ZERO);
//        splitRecord.setSplitCashAmounts(BigDecimal.ZERO);
//        splitRecord.setFeeYstAmounts(BigDecimal.ZERO);
//        BigDecimal feeSplits = new BigDecimal(0);
//        List<String> shouldSplit = new ArrayList<>();
//        shouldSplit.add("WeChat");
//        shouldSplit.add("ZhiFuBao");
//        Map<String, List<SmtSplitOrderFee>> groupMap = orderFees.stream().map(a -> {
//            if (shouldSplit.contains(a.getPayType()))
//                a.setPayType("TSY");
//            return a;
//        }).collect(Collectors.groupingBy(SmtSplitOrderFee::getPayType));
//        for (Map.Entry<String, List<SmtSplitOrderFee>> entry : groupMap.entrySet()) {
//            String payType = entry.getKey();
//            List<SmtSplitOrderFee> smtSplitOrderFeeList = entry.getValue();
//            if (smtSplitOrderFeeList == null || smtSplitOrderFeeList.size() == 0) continue;
//
//            SmtSplitOrderFee curOrderFee = smtSplitOrderFeeList.get(0);
//            String merName = curOrderFee.getMerName();
//
//            BigDecimal allSplit = smtSplitOrderFeeList.stream().map(SmtSplitOrderFee::getSplitAmounts).reduce(BigDecimal.ZERO, BigDecimal::add);
//            BigDecimal orderAmount = smtSplitOrderFeeList.stream().map(SmtSplitOrderFee::getOrderAmounts).reduce(BigDecimal.ZERO, BigDecimal::add);
//            ruleComs.forEach(cc -> {
//                SmtSplitOrderCom orderCom = new SmtSplitOrderCom();
//                orderCom.setMerchantId(merId);
//                orderCom.setMerName(merName);
//                orderCom.setComId(cc.getComId());
//                orderCom.setComType(cc.getComType());
//                orderCom.setComName(cc.getComName());
//                orderCom.setSplitAccount(cc.getAccount());
//
//                BigDecimal havPays = allSplit.multiply(cc.getAccount()).setScale(2, 4);
//                orderComsAdd(orderCom, 0, allSplit, havPays, payType, splitRecord.getId(), orderAmount);
//                orderComs.add(orderCom);
//                if (payType.equals("TSY"))
//                    splitRecord.setSplitYstAmounts(havPays.add(splitRecord.getSplitYstAmounts()));
//                else if (payType.equals("cash"))
//                    splitRecord.setSplitCashAmounts(havPays.add(splitRecord.getSplitCashAmounts()));
//            });
//
//            BigDecimal allFee = smtSplitOrderFeeList.stream().map(SmtSplitOrderFee::getFeeAmounts).reduce(BigDecimal.ZERO, BigDecimal::add);
//            SmtSplitOrderCom orderCom2 = new SmtSplitOrderCom();
//            orderCom2.setMerchantId(merId);
//            orderCom2.setMerName(merName);
//            //需要创建平台账号
//            orderCom2.setComId("1");
//            orderCom2.setComType("3");
//            orderCom2.setComName("意想意创");
//            orderCom2.setSplitAccount(new BigDecimal(1));
//            orderComsAdd(orderCom2, 1, allFee, allFee, payType, splitRecord.getId(), orderAmount);
//            orderComs.add(orderCom2);
//            if (payType.equals("TSY")) splitRecord.setFeeYstAmounts(allFee.add(splitRecord.getFeeYstAmounts()));
//        }
//        smtSplitOrderComService.saveOrUpdateBatch(orderComs);
//
//        recordMerPirce(orderComs);
//        splitRecord.setOrderComIds(orderComs.stream().map(smtSplitOrderCom -> String.valueOf(smtSplitOrderCom.getId())).collect(Collectors.joining(",")));
//        splitRecord.setSplitAmounts(splitRecord.getSplitYstAmounts().add(splitRecord.getSplitCashAmounts()));
//    }


//    void orderComsAdd(SmtSplitOrderCom orderCom, Integer type, BigDecimal allPays, BigDecimal havePays, String
//            payType, Integer recordId, BigDecimal reduce) {
//        orderCom.setRecordId(recordId);
//        orderCom.setOrderAmounts(reduce);
//        orderCom.setSplitAmounts(allPays);
//        orderCom.setReciveAmounts(havePays);
//
//        orderCom.setSplitType(payType);
//        if (type == 1) {
//            orderCom.setSplitType(payType);
//        }
//    }

    void orderComsAdd(SmtSplitOrderCom orderCom, Integer type, BigDecimal allPays, BigDecimal havePays, String
            payType, BigDecimal reduce) {
//        orderCom.setRecordId(recordId);
        orderCom.setOrderAmounts(reduce);
        orderCom.setSplitAmounts(allPays);
        orderCom.setReciveAmounts(havePays);

        orderCom.setSplitType(payType);
        if (type == 1) {
            orderCom.setSplitType(payType);
        }
    }

    private SmtSplitRecord getSmtSplitRecord(int recordId, String merId) {
        SmtSplitRecord splitRecord = new SmtSplitRecord();
//        if (recordId > 0) splitRecord = smtSplitRecordService.getById(splitRecord);
//        else {
        splitRecord.setMerchantId(merId);
        Dept dept = upmsHelloApi.queryByDept(Long.valueOf(merId));
        if (dept != null) {
            splitRecord.setMerName(dept.getName());
        }
        //merName
        smtSplitRecordService.save(splitRecord);
//        }
        return splitRecord;
    }

//    private void dodo(SmtSplitOrderFee smtSplitOrderFee, BigDecimal allFee, Integer recordId, String
//            merId, List<PayOrder> payOrderList, String type) {
//        initFeeOrder(smtSplitOrderFee, merId, type);
//        BigDecimal basicFee = BigDecimal.ZERO;
//        BigDecimal addFee = BigDecimal.ZERO;
//        int ruleFeeId = 0;
//        SmtSplitRuleFee smtSplitRuleFee = feeSplit(merId, type);
//        if (smtSplitRuleFee != null) {
//            ruleFeeId = smtSplitRuleFee.getId();
////            basicFee = allFee.multiply(smtSplitRuleFee.getBasicFee()).setScale(2, 4);
//            addFee = allFee.multiply(smtSplitRuleFee.getAddFee()).setScale(2, 4);
//        }
//        addFeeOrder(smtSplitOrderFee, allFee, ruleFeeId, basicFee, addFee, recordId, payOrderList);
//    }

    private void dodo(SmtSplitOrderFee smtSplitOrderFee, BigDecimal allFee, Integer recordId, String
            merId, PayOrder payOrder, String type) {
        initFeeOrder(smtSplitOrderFee, merId, type);
        BigDecimal basicFee = BigDecimal.ZERO;
        BigDecimal addFee = BigDecimal.ZERO;
        int ruleFeeId = 0;
        SmtSplitRuleFee smtSplitRuleFee = feeSplit(merId, type);
        if (smtSplitRuleFee != null) {
            ruleFeeId = smtSplitRuleFee.getId();
//            basicFee = allFee.multiply(smtSplitRuleFee.getBasicFee()).setScale(2, 4);
            addFee = allFee.multiply(smtSplitRuleFee.getAddFee()).setScale(2, 4);
        }
        addFeeOrder(smtSplitOrderFee, allFee, ruleFeeId, basicFee, addFee, recordId, payOrder);
    }

    private void initMecId() {
        LambdaQueryWrapper<PayOrder> lqw = new LambdaQueryWrapper<>();
        lqw.eq(PayOrder::getSplitType, 0);
        lqw.isNull(PayOrder::getMerchantId);
        List<PayOrder> payOrders = this.list(lqw);
        //

        Map<String, List<PayOrder>> groupMap = payOrders.stream().collect(Collectors.groupingBy(PayOrder::getDevCode));
        for (Map.Entry<String, List<PayOrder>> entry : groupMap.entrySet()) {
            String devCode = entry.getKey();
            List<PayOrder> payOrderList = entry.getValue();
            //获取设备merid
            SmtDev smtDev = smtDevService.queryDevCode(devCode);
            if (smtDev != null) {
                payOrderList.stream().peek(a -> a.setMerId(smtDev.getMerchantId())).collect(Collectors.toList());
            }
            this.updateBatchById(payOrderList);
        }
    }


    private SmtSplitRuleFee feeSplit(String merId, String splitType) {
        SmtSplitRuleFee smtSplitRuleFee = smtSplitRuleFeeService.qurySplitType(merId, splitType);
        return smtSplitRuleFee;
    }

    void initFeeOrder(SmtSplitOrderFee smtSplitOrderFee, String merId, String channelType) {
        smtSplitOrderFee.setMerchantId(merId);
        Dept dept = upmsHelloApi.queryByDept(Long.valueOf(merId));
        if (dept != null) {
            smtSplitOrderFee.setMerName(dept.getName());
        }
        smtSplitOrderFee.setPayType(channelType);
    }


//    void addFeeOrder(SmtSplitOrderFee smtSplitOrderFee, BigDecimal all, Integer ruleFeeId, BigDecimal
//            basicFee, BigDecimal addFee, Integer recordId, List<PayOrder> payOrderList) {
//        //手续费总金额
//        BigDecimal fee = basicFee.add(addFee);
//        BigDecimal subtract = all.subtract(fee);
//        String orderComIds = payOrderList.stream().map(payOrder -> {
//            return String.valueOf(payOrder.getId());
//        }).collect(Collectors.joining(","));
//        smtSplitOrderFee.setOrderIds(orderComIds);
//        smtSplitOrderFee.setOrderAmounts(all);
//        smtSplitOrderFee.setRuleFeeId(ruleFeeId);
//        smtSplitOrderFee.setSplitAmounts(subtract);
//        smtSplitOrderFee.setFeeAmounts(fee);
//        //添加分账记录id
//        smtSplitOrderFee.setRecordId(recordId);
//        smtSplitOrderFee.setFeeBasicAmounts(basicFee);
//        smtSplitOrderFee.setFeeAddAmounts(addFee);
//    }

    void addFeeOrder(SmtSplitOrderFee smtSplitOrderFee, BigDecimal all, Integer ruleFeeId, BigDecimal
            basicFee, BigDecimal addFee, Integer recordId, PayOrder payOrder) {
        //手续费总金额
        BigDecimal fee = basicFee.add(addFee);
        BigDecimal subtract = all.subtract(fee);
        smtSplitOrderFee.setOrderIds(String.valueOf(payOrder.getId()));
        smtSplitOrderFee.setOrderAmounts(all);
        smtSplitOrderFee.setRuleFeeId(ruleFeeId);
        smtSplitOrderFee.setSplitAmounts(subtract);
        smtSplitOrderFee.setFeeAmounts(fee);
        //添加分账记录id
        smtSplitOrderFee.setRecordId(recordId);
        smtSplitOrderFee.setFeeBasicAmounts(basicFee);
        smtSplitOrderFee.setFeeAddAmounts(addFee);
    }

    /**
     * 订单记录表
     */
    void recordMerPirce(List<SmtSplitOrderCom> smtSplitOrderCom) {
        if (CollectionUtils.isEmpty(smtSplitOrderCom)) {
            Map<String, List<SmtSplitOrderCom>> groupMap = smtSplitOrderCom.stream().collect(Collectors.groupingBy(SmtSplitOrderCom::getMerchantId));
            for (Map.Entry<String, List<SmtSplitOrderCom>> entry : groupMap.entrySet()) {
                String merId = entry.getKey();
                List<SmtSplitOrderCom> coms = entry.getValue();
                coms.forEach(aa -> {
                    SmtMerchantPrice smtMerchantPrice = new SmtMerchantPrice();
                    smtMerchantPrice.setMerchantId(merId);
                    smtMerchantPrice.setMerName(aa.getMerName());
                    smtMerchantPrice.setPrice(aa.getReciveAmounts());
                    smtMerchantPrice.setChannelType(aa.getSplitType());
                    smtMerchantPriceService.save(smtMerchantPrice);
                });
                BigDecimal allPrice = coms.stream().map(SmtSplitOrderCom::getReciveAmounts).reduce(BigDecimal.ZERO, BigDecimal::add);
                Dept dept = upmsHelloApi.queryByDept(Long.valueOf(merId));
                if (dept != null) {
                    dept.setMerchantBalance(allPrice);
                }
            }


        }
    }

}
